<?php
class RatingFilter extends AbstractFilter {

	protected $_criteria = null;
	
	public $rating;
	
	public function init($criteria) {
		$this->_criteria = $criteria;
		if (isset($_GET['rating'])) $this->rating = explode('_', $_GET['rating']);
	}
	
	public function apply() {
		if (!empty($this->rating)) {
			$r = implode(',', $this->rating);
			$this->_criteria->addAndCondition("rating IN ($r)", 'rating');
		}
	}

	public function getClearUrl() {
		$gets = $_GET;
		unset($gets['rating']);
		return Yii::app()->createAbsoluteUrl('site/index', $gets);
	}
	
	public function isApplied() {
		return isset($_GET['rating']);
	}
	
	public function getItems() {
		$c = clone $this->_criteria;
		$c->removeCondition('rating');
		$c->group = 'rating';
		$c->select = 'rating, COUNT(p.id) as count';
		$c->addAndCondition('rating > 0');
		$cmd = $c->getCommand();
		$cmd->from = Post::model()->tableName().' AS p';

		$data = $cmd->queryAll();
		$result = array();
		foreach($data as $d) {
			$result[$d['rating']] = ($d['rating']).' <span class="count">('.$d['count'].')</span>';
		}
		return $result;
	}
	
	public function getTemplate() {
		return '/catalog/filter/rating';
	}
	
}